<?php

namespace MicroCyanSpider\Plan\XiaoHongShu\Helper;

use GuzzleHttp\Client;

class Http
{
    /**
     * @var array
     */
    protected $headers= [
        'Accept'=>'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Encoding'=>'gzip, deflate, br',
        'Accept-Language'=>'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-CN;q=0.6',
        'Sec-Ch-Ua'=>'"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
        'Sec-Ch-Ua-Mobile'=>'?0',
        'Sec-Ch-Ua-Platform'=>'macOS',
        'Sec-Fetch-Dest'=>'document',
        'Sec-Fetch-Mode'=>'navigate',
        'Sec-Fetch-Site'=>'none',
        'Sec-Fetch-User'=>'?1',
        'Upgrade-Insecure-Requests'=>'1',
        'User-Agent'=>'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36'
    ];

    /**
     * @param string $method
     * @param string $uri
     * @param array $options
     * @return string
     * @throws \Exception
     */
    public function request(string $method,string $uri,array $options=[]): string
    {
        if (empty($this->headers['Cookie'])) throw new \Exception('Cookie未设置，请设置Cookie');
        if (!is_string($this->headers['Cookie']) || strpos($this->headers['Cookie'],'web_session')===false) throw new \Exception('Cookie设置不正确');
        $options['headers'] = array_merge($options['headers']??[],$this->headers);
        try {
            return (new Client())->request($method,$uri,$options)->getBody()->getContents();
        }catch (\GuzzleHttp\Exception\GuzzleException $exception){
            if (preg_match("/404.*not.*found/i",$exception->getMessage())){
                throw new \Exception('小红书笔记不存在或已删除');
            }
            throw new \Exception('Cookie用户已被限制访问');
        }
    }

    /**
     * @param string $cookie
     * @return $this
     */
    public function setCookie(string $cookie): Http
    {
        $this->headers['Cookie'] = $cookie;
        return $this;
    }
    /**
     * @param string $proxy
     * @return $this
     */
    public function setProxy(string $proxy): Http
    {
        if (!empty($proxy)){
            if (preg_match("/^[\w-]+:[\w-]+@[\d.]{5,16}:\d+$/",$proxy)){
                $this->headers['proxy'] = $proxy;
            }
        }
        return $this;
    }
    /**
     * @param array $headers
     * @return $this
     */
    public function setHeader(array $headers=[]): Http
    {
        $this->headers = array_merge($this->headers,$headers);
        return $this;
    }


}